package com.consumer;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import com.alibaba.fastjson.JSON;
import com.config.MQBusiHandler;
import com.model.MQMessageVO;
import com.model.RequestMessage;
import com.mqService.MQBaseServcie;
import com.mqService.MQMessageService;
import com.rabbitmq.client.Channel;
import com.util.SpringContextUtils;

/**
 * MQ消费者
 * @author IT-GYS
 *
 */
@Component
public class MqConsumer 
{
	@Autowired
	private MQMessageService messageService;
	@Autowired
	private MQBusiHandler handler;
	Logger logger = LoggerFactory.getLogger(MqConsumer.class);
	
	/**
	 * 监控Q1
	 * @param msg
	 * @param channel
	 * @param tag
	 */
	@RabbitHandler
	@RabbitListener(queues = "${rabbitmq.queue.topic1}")
	public void receiveRabbitmqMsg(Message msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag)
	{
	    try {
	    	byte[] b = msg.getBody();
	    	ByteArrayInputStream bais = new ByteArrayInputStream(b);
	    	ObjectInputStream ois = new ObjectInputStream(bais);
	    	RequestMessage<?> requestMessage = (RequestMessage<?>) ois.readObject();
	    	logger.info("{}:{}","接收到RabbitmqMsg",JSON.toJSONString(requestMessage));
	    	if(null == requestMessage) 
	    	{
	    		throw new RuntimeException("报文异常");
	    	}
	    	MQMessageVO message = new MQMessageVO();
    		message.setRequestID(requestMessage.getRequestID());
    		message.setStatus("0");
    		message.setServiceName(requestMessage.getServiceName());
    		message.setSourceSystem(requestMessage.getSourceSystem());
    		message.setTargetSystem(requestMessage.getTargetSystem());
    		message.setMessage(JSON.toJSONString(requestMessage.getData()));
    		message.setExchange(msg.getMessageProperties().getReceivedExchange());
    		message.setRouting(msg.getMessageProperties().getReceivedRoutingKey());
    		message.setQueue(msg.getMessageProperties().getConsumerQueue());
    		int insert = messageService.insert(message);
    		if(insert > 0) 
    		{
    			List<?> data = requestMessage.getData();
    	    	logger.info("body:{}",JSON.toJSONString(data));
    	    	String serviceName = requestMessage.getServiceName();
    	    	if(null == serviceName || !handler.getProps().containsKey(serviceName)) 
    	    	{
    	    		return;
    	    	}
    	    	Properties props = handler.getProps();
    	    	String fullName = props.getProperty(serviceName);
    	    	Class<?> service = Class.forName(fullName);
    	    	String name=service.getSimpleName();
    	    	MQBaseServcie<?> bean = (MQBaseServcie<?>) SpringContextUtils.getBean(name);
    	    	Method methods = bean.getClass().getDeclaredMethod("process", List.class);
    	        methods.setAccessible(true);
    	        methods.invoke(bean,data);
    		}
	    	//String body = new String(msg.getBody(),"utf-8");
	    }catch(Exception e){
	    	logger.error(e.getMessage());
	    }finally {

	    }
	}
	
	/**
	 * 监控Q2
	 * @param msg
	 * @param channel
	 * @param tag
	 */
	@RabbitHandler
	@RabbitListener(queues = "${rabbitmq.queue.topic2}")
	public void receiveRabbitmqMsg_topic(Message msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
		String funcName="接收到RabbitmqMsg";
	    logger.info("{}:{}",funcName,msg);
	}
}
